const dateUtils = require('../../utils/defautils')
const utils = require("../../utils/index.js")
const {
SendverificationCode,
register,
option,
    smscode,
follow
} = require('../../api/login.js')
const {
    levelOption,
    sheng,
} = require('../../api/index.js')
const request = require('../../api/request')
Page({
data: {
    leixingList: ["请选择导师类型", "校内导师", "校外导师"],
    leixingIndex: 0,
    xingbieList: ["请选择性别", "男", "女"],
    xingbieIndex: 0,
    xiangmufenleiList: ["请选择项目分类"],
    xiangmufenleiIndex: 0,
    chengshiList: ["请选择城市"],
    chengshiIndex: 0,
    xuexiaoList: ["请选择学校"],
    xuexiaoIndex: 0,
    yuanquList: ["请选择园区"],
    yuanquIndex: 0,
    daoshigonghao: '',
    mima: '',
    mima2: '',
    daoshixingming: '',
    touxiang: '',
    tempPathtouxiang: '../../static/upload.png',
    zhicheng: '',
    zhuanyejingyan: '',
    zhidaojingyan: '',
    suozaidanwei: '',
    gerenjianjie: '',
    lingyuzhuanzhang: '',
    xiangmuleixing: '',
    zhidaoguoxiangmu: '',
    youxiang: '',
    inputSmscode: '',
    canSendCode: true,
    buttonText: '发送验证码',
    countdown: 60,
    shoujihaoma: '',
    inputSmscode2: '',
    canSendSmsCode: true,
    buttonText2: '发送验证码',
    countdown2: 60,
    suozaiyuanxi: '', // 新增字段
    xueshubeijing: '', // 新增字段
},

async onLoad(options) {
  if (options && options.phone) {
    this.setData({ shoujihaoma: options.phone });
  }
},
onUnload() {
},
async onShow() {
    // 初始化下拉选项
    this.setData({
        leixingList: ["请选择导师类型", "校内导师", "校外导师"],
        xingbieList: ["请选择性别", "男", "女"],
        xiangmufenleiList: ["请选择项目分类"],
        chengshiList: ["请选择城市"],
        xuexiaoList: ["请选择学校"],
        yuanquList: ["请选择园区"]
    });
    // 拉取项目分类、城市、学校、园区数据
    const xiangmufenlei = await option('xiangmufenlei/xiangmufenlei');
    if (xiangmufenlei.data && xiangmufenlei.data.length) {
        this.setData({ xiangmufenleiList: ["请选择项目分类", ...xiangmufenlei.data], xiangmufenleiIndex: 0 });
    }
    const chengshi = await sheng("option/chengshi/chengshi");
    if (chengshi.data && chengshi.data.length) {
        this.setData({ chengshiList: ["请选择城市", ...chengshi.data], chengshiIndex: 0 });
    }
    const xuexiao = await option('xuexiao/xuexiao');
    if (xuexiao.data && xuexiao.data.length) {
        this.setData({ xuexiaoList: ["请选择学校", ...xuexiao.data], xuexiaoIndex: 0 });
    }
    const yuanqu = await option('yuanqu/yuanqu');
    if (yuanqu.data && yuanqu.data.length) {
        this.setData({ yuanquList: ["请选择园区", ...yuanqu.data], yuanquIndex: 0 });
    }
},







daoshigonghaoInput(e) {
this.setData({
    daoshigonghao: e.detail.value
})
},

mimaInput(e) {
this.setData({
    mima: e.detail.value
})
},

mima2Input(e) {
    this.setData({ mima2: e.detail.value });
},

daoshixingmingInput(e) {
this.setData({
    daoshixingming: e.detail.value
})
},


touxiangTap() {
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePaths = res.tempFilePaths;
let tempPathtouxiang= tempFilePaths[0]
// 本地临时图片的路径
this.setData({
    tempPathtouxiang,
})
// 上传网络图片
const  baseURL= wx.getStorageSync('baseURL')
    if(baseURL){
        wx.uploadFile({
            url: `${baseURL}/file/upload`,
            filePath: res.tempFilePaths[0],
            name: 'file',
            header: {
                'Token': wx.getStorageSync('token')
            },
            success: (uploadFileRes) => {
                let result = JSON.parse(uploadFileRes.data);
                // result.file是上传成功为网络图片的名称
                if (result.code == 0) {
                    this.setData({
                            touxiang: 'file/' + result.file
                    })
                } else {
                    wx.showToast({
                        title: result.msg,
                        icon: 'none',
                        duration: 2000
                    });
                }
            }
        })
    }



}
})
},

async sendCodeHandler() {
    if (!this.data.canSendCode) return;
    if (!this.data.youxiang) {
        wx.showToast({ title: '请输入邮箱', icon: 'none' });
        return;
    }
    if (!utils.validata('email', this.data.youxiang)) {
        wx.showToast({ title: '请输入有效邮箱', icon: 'none' });
        return;
    }
    // 按网页端方式调用接口
    const res = await request({
        url: `/daoshi/sendemail?email=${this.data.youxiang}`,
        method: 'get',
    });
    if (res.code === 0 || res.data?.code === 0) {
        wx.showToast({ title: '验证码发送成功', icon: 'success' });
        this.setData({ canSendCode: false });
        let time = this.data.countdown;
        let timer = setInterval(() => {
            time--;
            this.setData({ countdown: time });
            if (time <= 0) {
                clearInterval(timer);
                this.setData({ buttonText: '发送验证码', canSendCode: true, countdown: 60 });
            }
        }, 1000);
    } else {
        wx.showToast({ title: res.msg || (res.data && res.data.msg) || '发送失败', icon: 'none' });
    }
},

xingbieChange(e) {
const selectedIndex = e.detail.value;
    this.setData({
            xingbieIndex: selectedIndex,
    });
},

zhichengInput(e) {
this.setData({
    zhicheng: e.detail.value
})
},

xiangmufenleiChange(e) {
const selectedIndex = e.detail.value;
    this.setData({
            xiangmufenleiIndex: selectedIndex,
    });
},

leixingChange(e) {
const selectedIndex = e.detail.value;
    this.setData({
            leixingIndex: selectedIndex,
    });
},

zhuanyejingyanInput(e) {
this.setData({
    zhuanyejingyan: e.detail.value
})
},

zhidaojingyanInput(e) {
this.setData({
    zhidaojingyan: e.detail.value
})
},

xueshubeijingInput(e) {
this.setData({
    xueshubeijing: e.detail.value
})
},

suozaidanweiInput(e) {
this.setData({
    suozaidanwei: e.detail.value
})
},

youxiangInput(e) {
this.setData({
    youxiang: e.detail.value
})
},

suozaiyuanxiInput(e) {
this.setData({
    suozaiyuanxi: e.detail.value
})
},

gerenjianjieInput(e) {
this.setData({
    gerenjianjie: e.detail.value
})
},

lingyuzhuanzhangInput(e) {
this.setData({
    lingyuzhuanzhang: e.detail.value
})
},

xiangmuleixingInput(e) {
this.setData({
    xiangmuleixing: e.detail.value
})
},

zhidaoguoxiangmuInput(e) {
this.setData({
    zhidaoguoxiangmu: e.detail.value
})
},

gongzuojingliInput(e) {
this.setData({
    gongzuojingli: e.detail.value
})
},

async register() {
    const leixing = this.data.leixingList[this.data.leixingIndex];
    // 校验导师类型
    if (this.data.leixingIndex === 0) {
        wx.showToast({ title: '类型不能为空', icon: 'none' });
        return;
    }
    // 校验导师工号/账号
    if (!this.data.daoshigonghao) {
        wx.showToast({ title: leixing === '校内导师' ? '导师工号不能为空' : '账号不能为空', icon: 'none' });
        return;
    }
    // 校验密码
    if (!this.data.mima) {
        wx.showToast({ title: '密码不能为空', icon: 'none' });
        return;
    }
    if (!this.data.mima2) {
        wx.showToast({ title: '请输入确认密码', icon: 'none' });
        return;
    }
    if (this.data.mima !== this.data.mima2) {
        wx.showToast({ title: '两次密码输入不一致', icon: 'none' });
        return;
    }
    // 校验导师姓名
    if (!this.data.daoshixingming) {
        wx.showToast({ title: '导师姓名不能为空', icon: 'none' });
        return;
    }
    // 校验头像（可选，和网页端一致，上传后处理baseURL）
    let touxiang = this.data.touxiang;
    if (touxiang) {
        const regex = new RegExp(wx.getStorageSync("baseURL"), "g");
        touxiang = touxiang.replace(regex, "");
    }
    // 校验职称（校内导师必填）
    if (leixing === '校内导师' && !this.data.zhicheng) {
        wx.showToast({ title: '职称不能为空', icon: 'none' });
        return;
    }
    // 校验项目分类
    if (this.data.xiangmufenleiIndex === 0) {
        wx.showToast({ title: '项目分类不能为空', icon: 'none' });
        return;
    }
    // 校验专业经验
    if (!this.data.zhuanyejingyan) {
        wx.showToast({ title: '专业经验不能为空', icon: 'none' });
        return;
    }
    // 校验指导经验
    if (!this.data.zhidaojingyan) {
        wx.showToast({ title: '指导经验不能为空', icon: 'none' });
        return;
    }
    // 校验学术背景
    if (!this.data.xueshubeijing) {
        wx.showToast({ title: '学术背景不能为空', icon: 'none' });
        return;
    }
    // 校验所在单位（校外导师必填）
    if (leixing === '校外导师' && !this.data.suozaidanwei) {
        wx.showToast({ title: '所在单位不能为空', icon: 'none' });
        return;
    }
    // 校验邮箱
    if (!this.data.youxiang) {
        wx.showToast({ title: '邮箱不能为空', icon: 'none' });
        return;
    }
    if (!utils.validata('email', this.data.youxiang)) {
        wx.showToast({ title: '邮箱应输入邮件格式', icon: 'none' });
        return;
    }
    // 校验领域专长
    if (!this.data.lingyuzhuanzhang) {
        wx.showToast({ title: '领域专长不能为空', icon: 'none' });
        return;
    }
    // 校验可指导项目类型
    if (!this.data.xiangmuleixing) {
        wx.showToast({ title: '可指导项目类型不能为空', icon: 'none' });
        return;
    }
    // 校验手机号
    if (!this.data.shoujihaoma) {
        wx.showToast({ title: '手机号不能为空', icon: 'none' });
        return;
    }
    if (!/^1[3-9]\d{9}$/.test(this.data.shoujihaoma)) {
        wx.showToast({ title: '手机号格式不正确', icon: 'none' });
        return;
    }
    // 校验短信验证码
    if (!this.data.inputSmscode2) {
        wx.showToast({ title: '请输入短信验证码', icon: 'none' });
        return;
    }
    // 校验城市
    if (this.data.chengshiIndex === 0) {
        wx.showToast({ title: '城市不能为空', icon: 'none' });
        return;
    }
    // 校验学校/园区
    if (leixing === '校内导师' && this.data.xuexiaoIndex === 0) {
        wx.showToast({ title: '学校不能为空', icon: 'none' });
        return;
    }
    if (leixing === '校外导师' && this.data.yuanquIndex === 0) {
        wx.showToast({ title: '园区不能为空', icon: 'none' });
        return;
    }
    // 校验邮箱验证码
    if (!this.data.inputSmscode) {
        wx.showToast({ title: '请输入邮箱验证码', icon: 'none' });
        return;
    }
    // 构造请求数据
    const resultObj = {
        daoshigonghao: this.data.daoshigonghao,
        mima: this.data.mima,
        mima2: this.data.mima2,
        daoshixingming: this.data.daoshixingming,
        touxiang: touxiang,
        xingbie: this.data.xingbieList[this.data.xingbieIndex],
        zhicheng: this.data.zhicheng,
        xiangmufenlei: this.data.xiangmufenleiList[this.data.xiangmufenleiIndex],
        leixing: leixing,
        zhuanyejingyan: this.data.zhuanyejingyan,
        zhidaojingyan: this.data.zhidaojingyan,
        suozaidanwei: this.data.suozaidanwei,
        gerenjianjie: this.data.gerenjianjie,
        lingyuzhuanzhang: this.data.lingyuzhuanzhang,
        xiangmuleixing: this.data.xiangmuleixing,
        zhidaoguoxiangmu: this.data.zhidaoguoxiangmu,
        xueshubeijing: this.data.xueshubeijing,
        chengshi: this.data.chengshiList[this.data.chengshiIndex],
        xuexiao: this.data.xuexiaoList[this.data.xuexiaoIndex],
        yuanqu: this.data.yuanquList[this.data.yuanquIndex],
        shoujihaoma: this.data.shoujihaoma,
        youxiang: this.data.youxiang,
        emailCode: this.data.inputSmscode,
        smsCode: this.data.inputSmscode2,
        suozaiyuanxi: this.data.suozaiyuanxi,
    };
    // 新增：自动填充空字段为“无”
    Object.keys(resultObj).forEach(key => {
        if (resultObj[key] === undefined || resultObj[key] === null || resultObj[key] === '') {
            resultObj[key] = '无';
        }
    });
    // 调试日志
    console.log('注册请求数据:', resultObj);
    // 提交注册
    const res = await request({
        url: '/daoshi/register',
        method: 'post',
        data: resultObj,
        header: {
            'content-type': 'application/json'
        }
    });
    if (res.code == 0 || res.data?.code == 0) {
        wx.showToast({ title: '注册成功', icon: 'success' });
        wx.navigateTo({ url: '../login/login' });
    } else {
        wx.showToast({ title: res.msg || (res.data && res.data.msg) || '注册失败，请稍后重试', icon: 'none' });
    }
},

sendSmsCodeHandler: async function() {
    if (!this.data.canSendSmsCode) return;
    if (!this.data.shoujihaoma) {
        wx.showToast({ title: '请输入手机号', icon: 'none' });
        return;
    }
    // 手机号格式校验
    if (!/^1[3-9]\d{9}$/.test(this.data.shoujihaoma)) {
        wx.showToast({ title: '手机号格式不正确', icon: 'none' });
        return;
    }
    // 按网页端方式调用接口
    const res = await request({
        url: `/daoshi/sendsms?mobile=${this.data.shoujihaoma}`,
        method: 'get',
    });
    if (res.code === 0 || res.data?.code === 0) {
        wx.showToast({ title: '验证码发送成功', icon: 'success' });
        this.setData({ canSendSmsCode: false });
        let time = this.data.countdown2;
        let timer = setInterval(() => {
            time--;
            this.setData({ countdown2: time });
            if (time <= 0) {
                clearInterval(timer);
                this.setData({ buttonText2: '发送验证码', canSendSmsCode: true, countdown2: 60 });
            }
        }, 1000);
    } else {
        wx.showToast({ title: res.msg || (res.data && res.data.msg) || '发送失败', icon: 'none' });
    }
},

chengshiChange(e) {
    this.setData({ chengshiIndex: e.detail.value });
},

xuexiaoChange(e) {
    this.setData({ xuexiaoIndex: e.detail.value });
},

yuanquChange(e) {
    this.setData({ yuanquIndex: e.detail.value });
},

inputSmscodeInput(e) {
  this.setData({
    inputSmscode: e.detail.value
  })
},
inputSmscode2Input(e) {
  this.setData({
    inputSmscode2: e.detail.value
  })
},
shoujihaomaInput(e) {
  this.setData({
    shoujihaoma: e.detail.value
  })
},
});